﻿using System;
using System.Timers;
using Timer = System.Timers.Timer;

namespace EventDemo05050601
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello, World!");

            Connection connection = new Connection();
            Display display = new Display();
            connection.MessageReceived += display.DisplayMessage;
            connection.Connect();
            Console.ReadKey();
        }
    }

    public delegate void MeaasgeHandler(string messageText);
    public class Connection
    {
        Timer polltimer;
        public event MeaasgeHandler MessageReceived;

        public void Connect() => polltimer.Start();

        public void Disconnect() => polltimer.Stop();
        public Connection()
        {
            polltimer = new Timer(100);
            polltimer.Elapsed += new ElapsedEventHandler(Timer_Elapsed);
            polltimer.Start();
        }

        static Random Random = new Random();

        private void Timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            Console.WriteLine("Checking for messages...");
            if (Random.Next(9) == 0 && MessageReceived != null)
            {
                MessageReceived("Random message!");
            }
        }
    }

    public class Display
    {
        public void DisplayMessage(string messageText) => Console.WriteLine(messageText);
    }
   
}
